package org.noahsark.nsmessenger.security;

public abstract class MDCalculator {

	private byte[] mOriginalData = null;

	protected abstract byte[] calculate(byte[] data);

	public String getStringDigest(String data) throws NoInputMessageException {
		checkInput(data);
		setOriginalData(data);

		return bytes2HexDigits(calculate(mOriginalData));
	}

	public String getStringDigest(byte[] data) throws NoInputMessageException {
		checkInput(data);
		setOriginalData(data);

		return bytes2HexDigits(calculate(mOriginalData));
	}

	public byte[] getBytesDigest(String data) throws NoInputMessageException {
		checkInput(data);
		setOriginalData(data);

		return calculate(mOriginalData);
	}

	public byte[] getBytesDigest(byte[] data) throws NoInputMessageException {
		checkInput(data);
		setOriginalData(data);

		return calculate(mOriginalData);
	}

	private void setOriginalData(String data) {
		mOriginalData = data.getBytes();
	}

	private void setOriginalData(byte[] data) {
		mOriginalData = data;
	}

	private String bytes2HexDigits(byte[] data) {
		StringBuilder resultBuilder = new StringBuilder(16);
		int mask = 0xFF;

		for (int i = 0; i < data.length; i++) {
			String hexString = Integer.toHexString(data[i] & mask).toUpperCase();
			if (1 == hexString.length()) {
				resultBuilder.append("0");
			}
			resultBuilder.append(hexString);
		}

		return resultBuilder.toString();
	}

	private void checkInput(Object data) throws NoInputMessageException {
		if (null == data) {
			throw new NoInputMessageException();
		}
	}

}